const moment = require("moment");
const bcrypt = require("bcryptjs");
const utils = require("../utils/index");
const { poolQuery } = require("../utils/db");
const { getPageData } = require("../utils/pagination");
const userModel = require("../models/userModel");
const menuModel = require("../models/menuModel");
const loginModel = require("../models/loginModel");
const userService = {
  // 检查账号名是否存在
  checkUser: (type, req, res) => {
    return new Promise((resolve, reject) => {
      const { account, id } = req.body;
      poolQuery(loginModel.checkUserName, [account], (err, data) => {
        if (err) reject(err);
        if (data.length > 0) {
          const dataId = data[0].id;
          if (type === "add" || (type === "edit" && dataId !== id)) {
            reject("用户名已存在,请更换其他用户名");
          }
        }
        resolve();
      });
    });
  },
  checkUserId: (req) => {
    return new Promise((resolve, reject) => {
      const { id } = req.body;
      poolQuery(loginModel.checkUserId, [id], (err, data) => {
        if (err) reject(err);
        if (data.length === 0) {
          reject("用户不存在");
        }
        resolve();
      });
    });
  },
  // 获取用户绑定的菜单
  getUserMenu: (req, res) => {
    const { menu_ids } = req.user;
    if (!menu_ids) {
      return res.tip("用户菜单列表为空,请先联系管理员进行菜单绑定");
    }
    poolQuery(menuModel.getBindList(menu_ids), (err, data) => {
      if (err) return req.tip(err);
      if (data.length === 0) {
        return req.tip("用户菜单列表为空,请先联系管理员进行菜单绑定");
      }
      try {
        return res.send({
          code: 0,
          data: utils.arrToRouterTree(data),
          message: "成功获取菜单数据",
        });
      } catch (e) {
        return req.tip(err);
      }
    });
  },
  // 绑定菜单
  bindMenu: (req, res) => {
    const { id, menuIds } = req.body;
    poolQuery(
      userModel().bindMenu,
      [menuIds?.join(",") ?? "", id],
      (err, rows) => {
        if (err) res.tip(err);
        if (rows.affectedRows !== 1) return res.tip("用户菜单绑定失败");
        return res.tip("用户菜单绑定成功", 0);
      }
    );
  },
  // 添加用户
  addUser: (req, res) => {
    const params = {
      ...req.body,
      password: bcrypt.hashSync(req.body.password, 10),
      createTime: moment().format("YYYY-MM-DD HH:mm:ss"),
    };
    poolQuery(userModel().addUser, params, (err, rows) => {
      if (err) return res.tip(err);
      if (rows.affectedRows !== 1) return res.tip("用户信息添加失败");
      return res.tip("用户信息添加成功", 0);
    });
  },
  // 编辑用户
  editUser: (req, res) => {
    // 修改密码需通过单独接口调用,此处禁止修改用户密码
    if (req.body) {
      delete req.body.password;
    }
    poolQuery(userModel().editUser, [req.body, req.body.id], (err, rows) => {
      if (err) return res.tip(err);
      if (rows.affectedRows !== 1) return res.tip("用户信息修改失败");
      return res.tip("用户信息修改成功", 0);
    });
  },
  // 删除用户
  deleteUser: (req, res) => {
    if (req.body.id === 1) {
      return res.tip("超级管理员不可删除");
    }
    poolQuery(userModel().deleteUser, [req.params.id], (err, rows) => {
      if (err) return res.tip(err);
      if (rows.affectedRows !== 1) return res.tip("删除用户失败");
      return res.tip("用户删除成功", 0);
    });
  },
  // 获取用户列表
  getUserPage: (req, res) => {
    const params = req.body;
    const page = params.page ?? 1;
    const limit = params.limit ?? 10;
    const { tableName, listCondition } = userModel(params);

    // 获取分页数据
    getPageData(
      page,
      limit,
      tableName,
      listCondition,
      (error, list, totalCount) => {
        if (error) return res.tip(error);
        res.send({
          code: 0,
          data: {
            list: list.map((el) => ({ ...el, password: "" })), // 禁止将密码返回
            totalCount,
          },
          message: "已获取数据",
        });
        console.log(error, list, totalCount);
      }
    );
  },
  // 获取用户select数据
  getUserSelect: (res) => {
    poolQuery(userModel().getUserSelect, (err, data) => {
      if (err) return res.tip(err);
      return res.send({
        code: 0,
        data: data.map((el) => ({ ...el, password: "" })),
        message: "已获取数据",
      });
    });
  },
  getBindMenuInfo: (req, res) => {
    const { id } = req.params;
    poolQuery(userModel().userInfo, [id], (err, data) => {
      if (err || !data) return res.tip("无数据");
      try {
        const { menu_ids } = data[0];
        const idList = menu_ids.split(",").map((el) => parseInt(el));
        poolQuery(menuModel.getBindList(menu_ids), [], (error, row) => {
          if (error) return res.tip(error);
          const lastLevelList = row.filter(
            (el) => el.parent_id && !idList.includes(el)
          );
          return res.send({
            code: 0,
            data: lastLevelList.map((el) => el.id),
            message: "已获取数据",
          });
          console.log(lastLevelList);
        });
      } catch (e) {
        return res.tip(e);
      }
    });
  },
};
module.exports = userService;
